namespace DotNetNuke.Common
{
    using DotNetNuke.Common.Utilities;
    using DotNetNuke.Entities.Host;
    using DotNetNuke.Entities.Modules;
    using DotNetNuke.Entities.Portals;
    using DotNetNuke.Entities.Tabs;
    using DotNetNuke.Framework.Providers;
    using DotNetNuke.Security;
    using DotNetNuke.Security.Roles;
    using DotNetNuke.Services.FileSystem;
    using DotNetNuke.Services.Localization;
    using DotNetNuke.Services.Mail;
    using DotNetNuke.Services.Url.FriendlyUrl;
    using DotNetNuke.UI.Utilities;
    using Microsoft.VisualBasic;
    using Microsoft.VisualBasic.CompilerServices;
    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.IO;
    using System.Net;
    using System.Runtime.CompilerServices;
    using System.Runtime.InteropServices;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Text;
    using System.Threading;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Xml;
    using System.Xml.Serialization;

    /// -----------------------------------------------------------------------------
    /// Namespace:  DotNetNuke.Common
    /// Project:    DotNetNuke
    /// Module:     Globals
    /// -----------------------------------------------------------------------------
    /// <summary>
    /// This module contains global utility functions, constants, and enumerations.
    /// </summary>
    /// <remarks>
    /// </remarks>
    /// <history>
    /// [cnurse]	11/16/2004	documented
    /// </history>
    /// -----------------------------------------------------------------------------
    [StandardModule]
    public sealed class Globals
    {
        private static string _ApplicationMapPath;
        private static string _ApplicationPath;
        private static string _AssemblyPath;
        private static string _HostMapPath;
        private static string _HostPath;
        private static Hashtable _HostSettings;
        private static PerformanceSettings _PerformanceSetting;
        private static string _ServerName;
        public const string glbAboutPage = "about.htm";
        public const string glbAppCompany = "Perpetual Motion Interactive Systems Inc.";
        public const string glbAppDescription = "ASP.NET Open Source Portal Application";
        public const string glbAppTitle = "DotNetNuke";
        public const string glbAppUrl = "http://www.dotnetnuke.com";
        public const string glbAppVersion = "04.00.00";
        public const string glbConfigFile = @"\Install\dnn.config";
        public const string glbConfigFolder = @"\Config\";
        public const string glbDefaultAdminContainer = "Image Header - Color Background.ascx";
        public const string glbDefaultAdminSkin = "Horizontal Menu - Fixed Width.ascx";
        public const string glbDefaultContainer = "Image Header - Color Background.ascx";
        public const string glbDefaultContainerFolder = "/DNN-Blue/";
        public const string glbDefaultControlPanel = "Admin/ControlPanel/IconBar.ascx";
        public const string glbDefaultPage = "Default.aspx";
        public const string glbDefaultPane = "ContentPane";
        public const string glbDefaultSkin = "Horizontal Menu - Fixed Width.ascx";
        public const string glbDefaultSkinFolder = "/DNN-Blue/";
        public const string glbHelpUrl = "http://www.dotnetnuke.com/default.aspx?tabid=787";
        public const string glbHostSkinFolder = "_default";
        public const string glbImageFileTypes = "jpg,jpeg,jpe,gif,bmp,png,swf";
        public const string glbLegalCopyright = "DotNetNuke?is copyright 2002-YYYY by Perpetual Motion Interactive Systems Inc.";
        public const string glbRoleAllUsers = "-1";
        public const string glbRoleAllUsersName = "All Users";
        public const string glbRoleSuperUser = "-2";
        public const string glbRoleSuperUserName = "Superuser";
        public const string glbRoleUnauthUser = "-3";
        public const string glbRoleUnauthUserName = "Unauthenticated Users";
        public const int glbSuperUserAppName = -1;
        public const string glbTrademark = "DotNetNuke";

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// AddFile Uploads a single file
        /// </summary>
        /// <param name="strFileNamePath">The File Name of the File</param>
        /// <param name="strExtension">The extension of the file</param>
        /// <param name="strContentType">The mime type of the file</param>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [cnurse] 16/9/2004  Updated for localization, Help and 508
        /// [Philip Beadle] 6 October 2004 Moved to Globals from WebUpload.ascx.vb so can be accessed by URLControl.ascx
        /// </history>
        /// -----------------------------------------------------------------------------
        public static void AddFile(string strFileNamePath, string strExtension, [Optional, DefaultParameterValue("")] string strContentType)
        {
            int imageHeight=0;
            int imageWidth=0;
            PortalSettings _portalSettings = PortalController.GetCurrentPortalSettings();
            string strFileName = Path.GetFileName(strFileNamePath);
            string strFolderpath = GetSubFolderPath(strFileNamePath);
            if (strContentType == "")
            {
                string refStringHelperL0 = strExtension;
                if (refStringHelperL0 == "txt")
                {
                    strContentType = "text/plain";
                }
                else if ((((refStringHelperL0 == "htm") || (refStringHelperL0 == "html")) ? 1 : 0) != 0)
                {
                    strContentType = "text/html";
                }
                else if (refStringHelperL0 == "rtf")
                {
                    strContentType = "text/richtext";
                }
                else if ((((refStringHelperL0 == "jpg") || (refStringHelperL0 == "jpeg")) ? 1 : 0) != 0)
                {
                    strContentType = "image/jpeg";
                }
                else if (refStringHelperL0 == "gif")
                {
                    strContentType = "image/gif";
                }
                else if (refStringHelperL0 == "bmp")
                {
                    strContentType = "image/bmp";
                }
                else if ((((refStringHelperL0 == "mpg") || (refStringHelperL0 == "mpeg")) ? 1 : 0) != 0)
                {
                    strContentType = "video/mpeg";
                }
                else if (refStringHelperL0 == "avi")
                {
                    strContentType = "video/avi";
                }
                else if (refStringHelperL0 == "pdf")
                {
                    strContentType = "application/pdf";
                }
                else if ((((refStringHelperL0 == "doc") || (refStringHelperL0 == "dot")) ? 1 : 0) != 0)
                {
                    strContentType = "application/msword";
                }
                else
                {
                    if ((refStringHelperL0 == "csv") || (refStringHelperL0 == "xls"))
                    {
                    }
                    if (((refStringHelperL0 == "xlt") ? 1 : 0) != 0)
                    {
                        strContentType = "application/x-msexcel";
                    }
                    else
                    {
                        strContentType = "application/octet-stream";
                    }
                }
            }
            if (Convert.ToBoolean(Strings.InStr(1, "jpg,jpeg,jpe,gif,bmp,png,swf,", strExtension.ToLower() + ",", CompareMethod.Binary)))
            {
                try
                {
                    Image imgImage = Image.FromFile(strFileNamePath);
                    imageHeight = imgImage.Height;
                    imageWidth = imgImage.Width;
                    imgImage.Dispose();
                }
                catch (Exception exception1)
                {
                    
                    strContentType = "application/octet-stream";
                    
                }
            }
            FileController objFiles = new FileController();
            System.IO.FileInfo finfo = new System.IO.FileInfo(strFileNamePath);
            if (_portalSettings.ActiveTab.ParentId == _portalSettings.SuperTabId)
            {
                objFiles.AddFile(-1, strFileName, strExtension, finfo.Length, imageWidth, imageHeight, strContentType, strFolderpath);
            }
            else
            {
                objFiles.AddFile(_portalSettings.PortalId, strFileName, strExtension, finfo.Length, imageWidth, imageHeight, strContentType, strFolderpath);
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Adds HTTP to URL if no other protocol specified
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="strURL">The url</param>
        /// <returns>The formatted url</returns>
        /// <history>
        /// [cnurse]	12/16/2004	documented
        /// [cnurse]    05/06/2005  added chack for mailto: protocol
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string AddHTTP(string strURL)
        {
            if (strURL != "")
            {
                if (!((((Strings.InStr(1, strURL, "mailto:", CompareMethod.Binary) == 0) & (Strings.InStr(1, strURL, "://", CompareMethod.Binary) == 0)) & (Strings.InStr(1, strURL, "~", CompareMethod.Binary) == 0)) & (Strings.InStr(1, strURL, @"\\", CompareMethod.Binary) == 0)))
                {
                    return strURL;
                }
                if (HttpContext.Current.Request.IsSecureConnection)
                {
                    strURL = "https://" + strURL;
                    return strURL;
                }
                strURL = "http://" + strURL;
            }
            return strURL;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Generates the Application root url (including the tab/page)
        /// </summary>
        /// <remarks>
        /// This overload assumes the current page
        /// </remarks>
        /// <returns>The formatted root url</returns>
        /// <history>
        /// [cnurse]	12/16/2004	documented
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string ApplicationURL()
        {
            PortalSettings _portalSettings = PortalController.GetCurrentPortalSettings();
            if (_portalSettings != null)
            {
                return ApplicationURL(_portalSettings.ActiveTab.TabID);
            }
            return ApplicationURL(-1);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Generates the Application root url (including the tab/page)
        /// </summary>
        /// <remarks>
        /// This overload takes the tabid (page id) as a parameter
        /// </remarks>
        /// <param name="TabID">The id of the tab/page</param>
        /// <returns>The formatted root url</returns>
        /// <history>
        /// [cnurse]	12/16/2004	documented
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string ApplicationURL(int TabID)
        {
            string strURL = "~/Default.aspx";
            if (TabID != -1)
            {
                strURL = strURL + "?tabid=" + TabID.ToString();
            }
            return strURL;
        }

        public static DataSet BuildCrossTabDataSet(string DataSetName, IDataReader result, string FixedColumns, string VariableColumns, string KeyColumn, string FieldColumn, string FieldTypeColumn, string StringValueColumn, string NumericValueColumn)
        {
            string[] arrField;
            int intColumn;
            string[] arrFixedColumns = new string[0];
            string[] arrVariableColumns = new string[0];
            DataSet crosstab = new DataSet(DataSetName);
            crosstab.Namespace = "NetFrameWork";
            DataTable tab = new DataTable(DataSetName);
            arrFixedColumns = FixedColumns.Split(",".ToCharArray());
            int refIntHelperL0 = Information.UBound(arrFixedColumns, 1);
            for (intColumn = Information.LBound(arrFixedColumns, 1); intColumn <= refIntHelperL0; intColumn++)
            {
                arrField = arrFixedColumns[intColumn].Split("|".ToCharArray());
                DataColumn col = new DataColumn(arrField[0], Type.GetType("System." + arrField[1]));
                tab.Columns.Add(col);
            }
            if (VariableColumns != "")
            {
                arrVariableColumns = VariableColumns.Split(",".ToCharArray());
                int refIntHelperL1 = Information.UBound(arrVariableColumns, 1);
                intColumn = Information.LBound(arrVariableColumns, 1);
                while (intColumn <= refIntHelperL1)
                {
                    arrField = arrVariableColumns[intColumn].Split("|".ToCharArray());
                    DataColumn col = new DataColumn(arrField[0], Type.GetType("System." + arrField[1]));
                    col.AllowDBNull = true;
                    tab.Columns.Add(col);
                    intColumn++;
                }
            }
            crosstab.Tables.Add(tab);
            int intKeyColumn = -1;
            DataRow row = null;
            while (result.Read())
            {
                string FieldType;
                if (Convert.ToInt32(RuntimeHelpers.GetObjectValue(result[KeyColumn])) != intKeyColumn)
                {
                    if (intKeyColumn != -1)
                    {
                        tab.Rows.Add(row);
                    }
                    row = tab.NewRow();
                    int refIntHelperL2 = Information.UBound(arrFixedColumns, 1);
                    intColumn = Information.LBound(arrFixedColumns, 1);
                    while (intColumn <= refIntHelperL2)
                    {
                        arrField = arrFixedColumns[intColumn].Split("|".ToCharArray());
                        row[arrField[0]] = RuntimeHelpers.GetObjectValue(result[arrField[0]]);
                        intColumn++;
                    }
                    if (VariableColumns != "")
                    {
                        int refIntHelperL3 = Information.UBound(arrVariableColumns, 1);
                        for (intColumn = Information.LBound(arrVariableColumns, 1); intColumn <= refIntHelperL3; intColumn++)
                        {
                            arrField = arrVariableColumns[intColumn].Split("|".ToCharArray());
                            switch (arrField[1])
                            {
                                case "Decimal":
                                    row[arrField[0]] = 0;
                                    break;

                                case "String":
                                    row[arrField[0]] = "";
                                    break;
                            }
                        }
                    }
                    intKeyColumn = Convert.ToInt32(RuntimeHelpers.GetObjectValue(result[KeyColumn]));
                }
                if (FieldTypeColumn != "")
                {
                    FieldType = result[FieldTypeColumn].ToString();
                }
                else
                {
                    FieldType = "String";
                }
                switch (FieldType)
                {
                    case "Decimal":
                        row[Convert.ToInt32(RuntimeHelpers.GetObjectValue(result[FieldColumn]))] = RuntimeHelpers.GetObjectValue(result[NumericValueColumn]);
                        break;

                    case "String":
                        row[result[FieldColumn].ToString()] = RuntimeHelpers.GetObjectValue(result[StringValueColumn]);
                        break;
                }
            }
            result.Close();
            if (intKeyColumn != -1)
            {
                tab.Rows.Add(row);
            }
            crosstab.AcceptChanges();
            return crosstab;
        }

        public static string CleanFileName(string FileName)
        {
            return CleanFileName(FileName, "", "");
        }

        public static string CleanFileName(string FileName, string BadChars)
        {
            return CleanFileName(FileName, BadChars, "");
        }

        public static string CleanFileName(string FileName, string BadChars, string ReplaceChar)
        {
            string strFileName = FileName;
            if (BadChars == "")
            {
                BadChars = ":/\\?*|\"'\t";
            }
            if (ReplaceChar == "")
            {
                ReplaceChar = "_";
            }
            int refIntHelperL0 = Strings.Len(BadChars) - 1;
            for (int intCounter = 0; intCounter <= refIntHelperL0; intCounter++)
            {
                strFileName = strFileName.Replace(BadChars.Substring(intCounter, 1), ReplaceChar);
            }
            return strFileName;
        }

        public static string CloakText(string PersonalInfo)
        {
            if (PersonalInfo != null)
            {
                StringBuilder sb = new StringBuilder();
                sb.Remove(0, sb.Length);
                int StringLength = PersonalInfo.Length - 1;
                int refIntHelperL0 = StringLength;
                for (int i = 0; i <= refIntHelperL0; i++)
                {
                    sb.Append(Strings.Asc(PersonalInfo.Substring(i, 1)).ToString());
                    if (i < StringLength)
                    {
                        sb.Append(",");
                    }
                }
                StringBuilder sbScript = new StringBuilder();
                sbScript.Append("\r\n<script language=\"javascript\">\r\n");
                sbScript.Append("<!-- \r\n");
                sbScript.Append("   document.write(String.fromCharCode(" + sb.ToString() + "))\r\n");
                sbScript.Append("// -->\r\n");
                sbScript.Append("</script>\r\n");
                return sbScript.ToString();
            }
            return Null.NullString;
        }

        public static DataSet ConvertDataReaderToDataSet(IDataReader reader)
        {
            DataSet objDataSet = new DataSet();
            objDataSet.Tables.Add(ConvertDataReaderToDataTable(reader));
            return objDataSet;
        }

        public static DataTable ConvertDataReaderToDataTable(IDataReader reader)
        {
            DataTable objDataTable = new DataTable();
            int intFieldCount = reader.FieldCount;
            int refIntHelperL0 = intFieldCount - 1;
            for (int intCounter = 0; intCounter <= refIntHelperL0; intCounter++)
            {
                objDataTable.Columns.Add(reader.GetName(intCounter), reader.GetFieldType(intCounter));
            }
            objDataTable.BeginLoadData();
            object[] objValues = new object[(intFieldCount - 1) + 1];
            while (reader.Read())
            {
                reader.GetValues(objValues);
                objDataTable.LoadDataRow(objValues, true);
            }
            reader.Close();
            objDataTable.EndLoadData();
            return objDataTable;
        }

        public static void CreateRSS(IDataReader dr, string TitleField, string URLField, string CreatedDateField, string SyndicateField, string DomainName, string FileName)
        {
            PortalSettings _portalSettings = PortalController.GetCurrentPortalSettings();
            string strRSS = "";
            string strRelativePath = DomainName + Strings.Replace(Strings.Mid(FileName, Strings.InStr(1, FileName, @"\Portals", CompareMethod.Binary)), @"\", "/", 1, -1, CompareMethod.Binary);
            strRelativePath = Strings.Left(strRelativePath, Strings.InStrRev(strRelativePath, "/", -1, CompareMethod.Binary));
            while (dr.Read())
            {
                if (Convert.ToBoolean(RuntimeHelpers.GetObjectValue(dr[SyndicateField])))
                {
                    strRSS = (strRSS + "      <item>\r\n") + "         <title>" + dr[TitleField].ToString() + "</title>\r\n";
                    if (Strings.InStr(1, dr["URL"].ToString(), "://", CompareMethod.Binary) == 0)
                    {
                        if (Versioned.IsNumeric(dr["URL"].ToString()))
                        {
                            strRSS = strRSS + "         <link>" + DomainName + "/Default.aspx?tabid=" + dr[URLField].ToString() + "</link>\r\n";
                        }
                        else
                        {
                            strRSS = strRSS + "         <link>" + strRelativePath + dr[URLField].ToString() + "</link>\r\n";
                        }
                    }
                    else
                    {
                        strRSS = strRSS + "         <link>" + dr[URLField].ToString() + "</link>\r\n";
                    }
                    strRSS = (strRSS + "         <description>" + _portalSettings.PortalName + " " + GetMediumDate(dr[CreatedDateField].ToString()) + "</description>\r\n") + "     </item>\r\n";
                }
            }
            dr.Close();
            if (strRSS != "")
            {
                strRSS = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\r\n<rss version=\"0.91\">\r\n  <channel>\r\n     <title>" + _portalSettings.PortalName + "</title>\r\n     <link>" + DomainName + "</link>\r\n     <description>" + _portalSettings.PortalName + "</description>\r\n     <language>en-us</language>\r\n     <copyright>" + _portalSettings.FooterText + "</copyright>\r\n     <webMaster>" + _portalSettings.Email + "</webMaster>\r\n" + strRSS + "   </channel>\r\n</rss>";
                StreamWriter objStream = System.IO.File.CreateText(FileName);
                objStream.WriteLine(strRSS);
                objStream.Close();
            }
            else if (System.IO.File.Exists(FileName))
            {
                System.IO.File.Delete(FileName);
            }
        }

        public static string CreateValidID(string strID)
        {
            string strBadCharacters = @" ./-\";
            int refIntHelperL0 = strBadCharacters.Length - 1;
            for (int intIndex = 0; intIndex <= refIntHelperL0; intIndex++)
            {
                strID = strID.Replace(strBadCharacters.Substring(intIndex, 1), "_");
            }
            return strID;
        }

        public static string DateToString(DateTime DateValue)
        {
            string DateToString;
            try
            {
                if (!Null.IsNull(DateValue))
                {
                    return DateValue.ToString("s");
                }
                DateToString = Null.NullString;
            }
            catch (Exception exception1)
            {
                
                Exception ex = exception1;
                DateToString = Null.NullString;
                
                return DateToString;
                
            }
            return DateToString;
        }

        public static void DeleteFolderRecursive(string strRoot)
        {
            if ((strRoot != "") && Directory.Exists(strRoot))
            {
                foreach (string strFolder in Directory.GetDirectories(strRoot))
                {
                    DeleteFolderRecursive(strFolder);
                }
                foreach (string strFile in Directory.GetFiles(strRoot))
                {
                    try
                    {
                        System.IO.File.SetAttributes(strFile, FileAttributes.Normal);
                        System.IO.File.Delete(strFile);
                    }
                    catch (Exception exception1)
                    {
                        
                        
                    }
                }
                try
                {
                    Directory.Delete(strRoot);
                }
                catch (Exception exception2)
                {
                    ProjectData.SetProjectError(exception2);
                    
                }
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// DeserializeHashTableBase64 deserializes a Hashtable using Binary Formatting
        /// </summary>
        /// <remarks>
        /// While this method of serializing is no longer supported (due to Medium Trust
        /// issue, it is still required for upgrade purposes.
        /// </remarks>
        /// <param name="Source">The String Source to deserialize</param>
        /// <returns>The deserialized Hashtable</returns>
        /// <history>
        /// [cnurse]	2/16/2005	moved to Globals
        /// </history>
        /// -----------------------------------------------------------------------------
        public static Hashtable DeserializeHashTableBase64(string Source)
        {
            if (Source != "")
            {
                Hashtable objHashTable;
                MemoryStream mem = new MemoryStream(Convert.FromBase64String(Source));
                BinaryFormatter bin = new BinaryFormatter();
                try
                {
                    objHashTable = (Hashtable) bin.Deserialize(mem);
                }
                catch (Exception exception1)
                {
                    
                    Exception ex = exception1;
                    objHashTable = new Hashtable();
                    
                }
                mem.Close();
                return objHashTable;
            }
            return new Hashtable();
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// DeserializeHashTableXml deserializes a Hashtable using Xml Serialization
        /// </summary>
        /// <remarks>
        /// This is the preferred method of serialization under Medium Trust
        /// </remarks>
        /// <param name="Source">The String Source to deserialize</param>
        /// <returns>The deserialized Hashtable</returns>
        /// <history>
        /// [cnurse]	2/16/2005	created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static Hashtable DeserializeHashTableXml(string Source)
        {
            if (Source != "")
            {
                IEnumerator refObjectHelperL0=null;
                Hashtable objHashTable = new Hashtable();
                XmlDocument xmlProfile = new XmlDocument();
                xmlProfile.LoadXml(Source);
                try
                {
                    refObjectHelperL0 = xmlProfile.SelectNodes("profile/item").GetEnumerator();
                    while (refObjectHelperL0.MoveNext())
                    {
                        XmlElement xmlItem = (XmlElement) refObjectHelperL0.Current;
                        string key = xmlItem.GetAttribute("key");
                        XmlSerializer xser = new XmlSerializer(Type.GetType(xmlItem.GetAttribute("type")));
                        XmlTextReader reader = new XmlTextReader(new StringReader(xmlItem.InnerXml));
                        objHashTable.Add(key, RuntimeHelpers.GetObjectValue(xser.Deserialize(reader)));
                    }
                }
                finally
                {
                    if (refObjectHelperL0 is IDisposable)
                    {
                        (refObjectHelperL0 as IDisposable).Dispose();
                    }
                }
                return objHashTable;
            }
            return new Hashtable();
        }

        public static string EncodeReservedCharacters(string QueryString)
        {
            QueryString = QueryString.Replace("$", "%24");
            QueryString = QueryString.Replace("&", "%26");
            QueryString = QueryString.Replace("+", "%2B");
            QueryString = QueryString.Replace(",", "%2C");
            QueryString = QueryString.Replace("/", "%2F");
            QueryString = QueryString.Replace(":", "%3A");
            QueryString = QueryString.Replace(";", "%3B");
            QueryString = QueryString.Replace("=", "%3D");
            QueryString = QueryString.Replace("?", "%3F");
            QueryString = QueryString.Replace("@", "%40");
            return QueryString;
        }

        public static Control FindControlRecursive(Control objControl, string strControlName)
        {
            if (objControl.Parent == null)
            {
                return null;
            }
            if (objControl.Parent.FindControl(strControlName) != null)
            {
                return objControl.Parent.FindControl(strControlName);
            }
            return FindControlRecursive(objControl.Parent, strControlName);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Searches control hierarchy from top down to find a control matching the passed in name
        /// </summary>
        /// <param name="objParent">Root control to begin searching</param>
        /// <param name="strControlName">Name of control to look for</param>
        /// <returns></returns>
        /// <remarks>
        /// This differs from FindControlRecursive in that it looks down the control hierarchy, whereas, the 
        /// FindControlRecursive starts at the passed in control and walks the tree up.  Therefore, this function is 
        /// more a expensive task.
        /// </remarks>
        /// <history>
        /// [Jon Henning]	9/17/2004	Created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static Control FindControlRecursiveDown(Control objParent, string strControlName)
        {
            Control objCtl = objParent.FindControl(strControlName);
            if (objCtl == null)
            {
                IEnumerator refObjectHelperL0=null;
                try
                {
                    refObjectHelperL0 = objParent.Controls.GetEnumerator();
                    while (refObjectHelperL0.MoveNext())
                    {
                        Control objChild = (Control) refObjectHelperL0.Current;
                        objCtl = FindControlRecursiveDown(objChild, strControlName);
                        if (objCtl != null)
                        {
                            return objCtl;
                        }
                    }
                }
                finally
                {
                    if (refObjectHelperL0 is IDisposable)
                    {
                        (refObjectHelperL0 as IDisposable).Dispose();
                    }
                }
            }
            return objCtl;
        }

        public static string FormatAddress(object Unit, object Street, object City, object Region, object Country, object PostalCode)
        {
            string strAddress = "";
            if ((Unit != null) && (Strings.Trim(Unit.ToString()) != ""))
            {
                strAddress = strAddress + ", " + Unit.ToString();
            }
            if ((Street != null) && (Strings.Trim(Street.ToString()) != ""))
            {
                strAddress = strAddress + ", " + Street.ToString();
            }
            if ((City != null) && (Strings.Trim(City.ToString()) != ""))
            {
                strAddress = strAddress + ", " + City.ToString();
            }
            if ((Region != null) && (Strings.Trim(Region.ToString()) != ""))
            {
                strAddress = strAddress + ", " + Region.ToString();
            }
            if ((Country != null) && (Strings.Trim(Country.ToString()) != ""))
            {
                strAddress = strAddress + ", " + Country.ToString();
            }
            if ((PostalCode != null) && (Strings.Trim(PostalCode.ToString()) != ""))
            {
                strAddress = strAddress + ", " + PostalCode.ToString();
            }
            if (Strings.Trim(strAddress) != "")
            {
                strAddress = Strings.Mid(strAddress, 3);
            }
            return strAddress;
        }

        [Obsolete("This function has been replaced by DotNetNuke.Common.Utilities.HtmlUtils.FormatEmail")]
        public static string FormatEmail(string Email)
        {
            return HtmlUtils.FormatEmail(Email);
        }

        public static string FormatHelpUrl(string HelpUrl, PortalSettings objPortalSettings, string Name)
        {
            return FormatHelpUrl(HelpUrl, objPortalSettings, Name, "");
        }

        public static string FormatHelpUrl(string HelpUrl, PortalSettings objPortalSettings, string Name, string Version)
        {
            string strURL = HelpUrl;
            if (strURL.IndexOf("?") != -1)
            {
                strURL = strURL + "&helpculture=";
            }
            else
            {
                strURL = strURL + "?helpculture=";
            }
            if (Thread.CurrentThread.CurrentCulture.ToString().ToLower() != "")
            {
                strURL = strURL + Thread.CurrentThread.CurrentCulture.ToString().ToLower();
            }
            else
            {
                strURL = strURL + objPortalSettings.DefaultLanguage.ToLower();
            }
            if (Name != "")
            {
                strURL = strURL + "&helpmodule=" + HttpUtility.UrlEncode(Name);
            }
            if (Version != "")
            {
                strURL = strURL + "&helpversion=" + HttpUtility.UrlEncode(Version);
            }
            return AddHTTP(strURL);
        }

        [Obsolete("This function has been replaced by DotNetNuke.Common.Utilities.HtmlUtils.FormatWebsite")]
        public static string FormatWebsite(object Website)
        {
            return HtmlUtils.FormatWebsite(RuntimeHelpers.GetObjectValue(Website));
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Generates the correctly formatted friendly url.
        /// </summary>
        /// <remarks>
        /// Assumes Default.aspx, and that portalsettings are saved to Context
        /// </remarks>
        /// <param name="tab">The current tab</param>
        /// <param name="path">The path to format.</param>
        /// <returns>The formatted (friendly) url</returns>
        /// <history>
        /// [cnurse]	12/16/2004	documented
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string FriendlyUrl(DotNetNuke.Entities.Tabs.TabInfo tab, string path)
        {
            return FriendlyUrl(tab, path, "Default.aspx");
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Generates the correctly formatted friendly url
        /// </summary>
        /// <remarks>
        /// This overload includes the portal settings for the site
        /// </remarks>
        /// <param name="tab">The current tab</param>
        /// <param name="path">The path to format.</param>
        /// <param name="settings">The portal Settings</param>
        /// <returns>The formatted (friendly) url</returns>
        /// <history>
        /// [cnurse]	12/16/2004	documented
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string FriendlyUrl(DotNetNuke.Entities.Tabs.TabInfo tab, string path, PortalSettings settings)
        {
            return FriendlyUrl(tab, path, "Default.aspx", settings);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Generates the correctly formatted friendly url
        /// </summary>
        /// <remarks>
        /// This overload includes an optional page to include in the url.
        /// </remarks>
        /// <param name="tab">The current tab</param>
        /// <param name="path">The path to format.</param>
        /// <param name="pageName">The page to include in the url.</param>
        /// <returns>The formatted (friendly) url</returns>
        /// <history>
        /// [cnurse]	12/16/2004	documented
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string FriendlyUrl(DotNetNuke.Entities.Tabs.TabInfo tab, string path, string pageName)
        {
            PortalSettings _portalSettings = PortalController.GetCurrentPortalSettings();
            return FriendlyUrl(tab, path, pageName, _portalSettings);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Generates the correctly formatted friendly url
        /// </summary>
        /// <remarks>
        /// This overload includes an optional page to include in the url, and the portal 
        /// settings for the site
        /// </remarks>
        /// <param name="tab">The current tab</param>
        /// <param name="path">The path to format.</param>
        /// <param name="pageName">The page to include in the url.</param>
        /// <param name="settings">The portal Settings</param>
        /// <returns>The formatted (friendly) url</returns>
        /// <history>
        /// [cnurse]	12/16/2004	documented
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string FriendlyUrl(DotNetNuke.Entities.Tabs.TabInfo tab, string path, string pageName, PortalSettings settings)
        {
            return FriendlyUrlProvider.Instance().FriendlyUrl(tab, path, pageName, settings);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Generates the correctly formatted friendly url
        /// </summary>
        /// <remarks>
        /// This overload includes an optional page to include in the url, and the portal 
        /// settings for the site
        /// </remarks>
        /// <param name="tab">The current tab</param>
        /// <param name="path">The path to format.</param>
        /// <param name="pageName">The page to include in the url.</param>
        /// <param name="portalAlias">The portal Alias for the site</param>
        /// <returns>The formatted (friendly) url</returns>
        /// <history>
        /// [cnurse]	12/16/2004	documented
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string FriendlyUrl(DotNetNuke.Entities.Tabs.TabInfo tab, string path, string pageName, string portalAlias)
        {
            return FriendlyUrlProvider.Instance().FriendlyUrl(tab, path, pageName, portalAlias);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// GenerateTabPath generates the TabPath used in Friendly URLS
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="ParentId">The Id of the Parent Tab</param>
        /// <param name="TabName">The Name of the current Tab</param>
        /// <returns>The TabPath</returns>
        /// <history>
        /// [cnurse]	1/28/2005	documented
        /// modified to remove characters not allowed in urls
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string GenerateTabPath(int ParentId, string TabName)
        {
            string strTabPath = "";
            TabController objTabs = new TabController();
            DotNetNuke.Entities.Tabs.TabInfo objTab = objTabs.GetTab(ParentId);
            while (objTab != null)
            {
                string strTabName = HtmlUtils.StripNonWord(objTab.TabName, false);
                strTabPath = "//" + strTabName + strTabPath;
                if (Null.IsNull(objTab.ParentId))
                {
                    objTab = null;
                }
                else
                {
                    objTab = objTabs.GetTab(objTab.ParentId);
                }
            }
            return (strTabPath + "//" + HtmlUtils.StripNonWord(TabName, false));
        }

        public static string GetAbsoluteServerPath(HttpRequest Request)
        {
            string strServerPath = Request.MapPath(Request.ApplicationPath);
            if (!strServerPath.EndsWith(@"\"))
            {
                strServerPath = strServerPath + @"\";
            }
            return strServerPath;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets the ApplicationName for the MemberRole API.
        /// </summary>
        /// <remarks>
        /// This overload is used to get the current ApplcationName.  The Application
        /// Name is in the form Prefix_Id, where Prefix is the object qualifier
        /// for this instance of DotNetNuke, and Id is the current PortalId for normal
        /// users or glbSuperUserAppName for SuperUsers.
        /// </remarks>
        /// <history>
        /// [cnurse]	01/18/2005	documented and modifeid to handle a Prefix
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string GetApplicationName()
        {
            if (Convert.ToString(RuntimeHelpers.GetObjectValue(HttpContext.Current.Items["ApplicationName"])) == "")
            {
                PortalSettings _PortalSettings = PortalController.GetCurrentPortalSettings();
                if (_PortalSettings == null)
                {
                    return "/";
                }
                return GetApplicationName(_PortalSettings.PortalId);
            }
            return Convert.ToString(RuntimeHelpers.GetObjectValue(HttpContext.Current.Items["ApplicationName"]));
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets the ApplicationName for the MemberRole API.
        /// </summary>
        /// <remarks>
        /// This overload is used to build the Application Name from the Portal Id
        /// </remarks>
        /// <history>
        /// [cnurse]	01/18/2005	documented and modifeid to handle a Prefix
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string GetApplicationName(int PortalID)
        {
            ProviderConfiguration _providerConfiguration = ProviderConfiguration.GetProviderConfiguration("data");
            Provider objProvider = (Provider) _providerConfiguration.Providers[_providerConfiguration.DefaultProvider];
            string _objectQualifier = objProvider.Attributes["objectQualifier"];
            if ((_objectQualifier != "") & !_objectQualifier.EndsWith("_"))
            {
                _objectQualifier = _objectQualifier + "_";
            }
            return (_objectQualifier + Convert.ToString(PortalID));
        }

        public static XmlNode GetContent(string Content, string ContentType)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(Content);
            if (ContentType == "")
            {
                return xmlDoc.DocumentElement;
            }
            return xmlDoc.SelectSingleNode(ContentType);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// GetDatabaseVersion - gets the current version in the DB
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <returns>The DB Version</returns>
        /// <history>
        /// [cnurse]	02/02/2004	created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string GetDatabaseVersion()
        {
            string strDatabaseVersion = "";
            try
            {
                IDataReader dr = PortalSettings.GetDatabaseVersion();
                if (dr.Read())
                {
                    strDatabaseVersion = Strings.Format(RuntimeHelpers.GetObjectValue(dr["Major"]), "00") + Strings.Format(RuntimeHelpers.GetObjectValue(dr["Minor"]), "00") + Strings.Format(RuntimeHelpers.GetObjectValue(dr["Build"]), "00");
                }
                dr.Close();
            }
            catch (Exception exception1)
            {
                
                Exception ex = exception1;
                strDatabaseVersion = "ERROR:" + ex.Message;
                
            }
            return strDatabaseVersion;
        }

        public static string GetDBConnectionString()
        {
            return Config.GetSetting("SiteSqlServer");
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// GetDesktopModuleByName is a Utility function that retrieves the Desktop Module
        /// defeined by the name provided.
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="name">The Name of the Module</param>
        /// <returns>The Desktop Module</returns>
        /// <history>
        /// [cnurse]	4/22/2005	created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static DesktopModuleInfo GetDesktopModuleByName(string name)
        {
            DesktopModuleController objDesktopModules = new DesktopModuleController();
            DesktopModuleInfo objDesktopModule = objDesktopModules.GetDesktopModuleByModuleName(name);
            if (objDesktopModule == null)
            {
                objDesktopModule = objDesktopModules.GetDesktopModuleByFriendlyName(name);
            }
            return objDesktopModule;
        }

        public static string GetDomainName(HttpRequest Request)
        {
            StringBuilder DomainName = new StringBuilder();
            string URI = Request.Url.ToString();
            int intURL = Strings.InStr(URI, "?", CompareMethod.Binary);
            if (intURL > 0)
            {
                URI = Strings.Left(URI, intURL - 1);
            }
            string[] URL = Strings.Split(URI, "/", -1, CompareMethod.Binary);
            int refIntHelperL0 = URL.GetUpperBound(0);
            for (intURL = 2; intURL <= refIntHelperL0; intURL++)
            {
                string refStringHelperL0 = URL[intURL].ToLower();
                if ((((refStringHelperL0 == "admin") || (refStringHelperL0 == "controls")) || (refStringHelperL0 == "desktopmodules")) || ((refStringHelperL0 == "mobilemodules") || (refStringHelperL0 == "premiummodules")))
                {
                }
                if ((((refStringHelperL0 == "providers") ? 1 : 0) != 0) || ((URL[intURL].Length >= ".aspx".Length) && ((Strings.InStrRev(URL[intURL], ".aspx", -1, CompareMethod.Binary) == (URL[intURL].Length - (".aspx".Length - 1))) | (Strings.InStrRev(URL[intURL], ".axd", -1, CompareMethod.Binary) == (URL[intURL].Length - (".axd".Length - 1))))))
                {
                    break;
                }
                DomainName.Append(Interaction.IIf(DomainName.ToString() != "", "/", "").ToString() + URL[intURL]);
            }
            return DomainName.ToString();
        }

        public static HttpWebRequest GetExternalRequest(string Address)
        {
            PortalSettings _portalSettings = PortalController.GetCurrentPortalSettings();
            HttpWebRequest objRequest = (HttpWebRequest) WebRequest.Create(Address);
            if (HostSettings["WebRequestTimeout"] != null)
            {
                objRequest.Timeout = int.Parse(Conversions.ToString(HostSettings["WebRequestTimeout"]));
            }
            else
            {
                objRequest.Timeout = 0x2710;
            }
            objRequest.UserAgent = "DotNetNuke";
            if (Conversions.ToString(HostSettings["ProxyServer"]) != "")
            {
                WebProxy Proxy = new WebProxy(Conversions.ToString(HostSettings["ProxyServer"]), Convert.ToInt32(RuntimeHelpers.GetObjectValue(HostSettings["ProxyPort"])));
                if (Conversions.ToString(HostSettings["ProxyUsername"]) != "")
                {
                    NetworkCredential ProxyCredentials = new NetworkCredential(Conversions.ToString(HostSettings["ProxyUsername"]), Conversions.ToString(HostSettings["ProxyPassword"]));
                    Proxy.Credentials = ProxyCredentials;
                }
                objRequest.Proxy = Proxy;
            }
            return objRequest;
        }

        public static HttpWebRequest GetExternalRequest(string Address, NetworkCredential Credentials)
        {
            PortalSettings _portalSettings = PortalController.GetCurrentPortalSettings();
            HttpWebRequest objRequest = (HttpWebRequest) WebRequest.Create(Address);
            if (HostSettings["WebRequestTimeout"] != null)
            {
                objRequest.Timeout = int.Parse(Conversions.ToString(HostSettings["WebRequestTimeout"]));
            }
            else
            {
                objRequest.Timeout = 0x2710;
            }
            objRequest.UserAgent = "DotNetNuke";
            if (Credentials.UserName != null)
            {
                objRequest.Credentials = Credentials;
            }
            if (Conversions.ToString(HostSettings["ProxyServer"]) != "")
            {
                WebProxy Proxy = new WebProxy(Conversions.ToString(HostSettings["ProxyServer"]), Convert.ToInt32(RuntimeHelpers.GetObjectValue(HostSettings["ProxyPort"])));
                if (Conversions.ToString(HostSettings["ProxyUsername"]) != "")
                {
                    NetworkCredential ProxyCredentials = new NetworkCredential(Conversions.ToString(HostSettings["ProxyUsername"]), Conversions.ToString(HostSettings["ProxyPassword"]));
                    Proxy.Credentials = ProxyCredentials;
                }
                objRequest.Proxy = Proxy;
            }
            return objRequest;
        }

        public static ArrayList GetFileList(DirectoryInfo CurrentDirectory, [Optional, DefaultParameterValue("")] string strExtensions, [Optional, DefaultParameterValue(true)] bool NoneSpecified)
        {
            ArrayList arrFileList = new ArrayList();
            string strExtension = "";
            if (NoneSpecified)
            {
                arrFileList.Add(new FileItem("", "<" + DotNetNuke.Services.Localization.Localization.GetString("None_Specified") + ">"));
            }
            foreach (string File in Directory.GetFiles(CurrentDirectory.FullName))
            {
                if (Convert.ToBoolean(Strings.InStr(1, File, ".", CompareMethod.Binary)))
                {
                    strExtension = Strings.Mid(File, Strings.InStrRev(File, ".", -1, CompareMethod.Binary) + 1);
                }
                string FileName = File.Substring(CurrentDirectory.FullName.Length);
                if ((Strings.InStr(1, strExtensions.ToUpper(), strExtension.ToUpper(), CompareMethod.Binary) != 0) | (strExtensions == ""))
                {
                    arrFileList.Add(new FileItem(FileName, FileName));
                }
            }
            return arrFileList;
        }

        public static ArrayList GetFileList([Optional, DefaultParameterValue(-1)] int PortalId, [Optional, DefaultParameterValue("")] string strExtensions, [Optional, DefaultParameterValue(true)] bool NoneSpecified, [Optional, DefaultParameterValue("")] string Folder)
        {
            ArrayList arrFileList = new ArrayList();
            if (NoneSpecified)
            {
                arrFileList.Add(new FileItem("", "<" + DotNetNuke.Services.Localization.Localization.GetString("None_Specified") + ">"));
            }
            IDataReader dr = new FileController().GetFiles(PortalId, Folder);
            while (dr.Read())
            {
                if ((Strings.InStr(1, strExtensions.ToUpper(), dr["Extension"].ToString().ToUpper(), CompareMethod.Binary) != 0) | (strExtensions == ""))
                {
                    arrFileList.Add(new FileItem(dr["FileID"].ToString(), dr["FileName"].ToString()));
                }
            }
            dr.Close();
            return arrFileList;
        }

        public static string GetHashValue(object HashObject, string DefaultValue)
        {
            if (HashObject != null)
            {
                if (Convert.ToString(RuntimeHelpers.GetObjectValue(HashObject)) != "")
                {
                    return Convert.ToString(RuntimeHelpers.GetObjectValue(HashObject));
                }
                return DefaultValue;
            }
            return DefaultValue;
        }

        public static PortalSettings GetHostPortalSettings()
        {
            int TabId = -1;
            int PortalId = -1;
            PortalAliasInfo objPortalAliasInfo = null;
            if (Convert.ToString(RuntimeHelpers.GetObjectValue(HostSettings["HostPortalId"])) != "")
            {
                objPortalAliasInfo = new PortalAliasInfo();
                objPortalAliasInfo.PortalID = int.Parse(Convert.ToString(RuntimeHelpers.GetObjectValue(HostSettings["HostPortalId"])));
                PortalId = objPortalAliasInfo.PortalID;
            }
            return new PortalSettings(TabId, objPortalAliasInfo);
        }

        public static string GetMediumDate(string strDate)
        {
            if (strDate != "")
            {
                DateTime datDate = Convert.ToDateTime(strDate);
                string strYear = DateAndTime.Year(datDate).ToString();
                string strMonth = DateAndTime.MonthName(DateAndTime.Month(datDate), true);
                string strDay = DateAndTime.Day(datDate).ToString();
                strDate = strDay + "-" + strMonth + "-" + strYear;
            }
            return strDate;
        }

        public static string GetOnLineHelp(string HelpUrl, ModuleInfo moduleConfig)
        {
            bool isAdminModule = moduleConfig.IsAdmin;
            string showOnlineHelp = Conversions.ToString(HostSettings["EnableModuleOnLineHelp"]);
            string ctlString = HttpContext.Current.Request.QueryString["ctl"];
            if (((showOnlineHelp == "Y") & !isAdminModule) | isAdminModule)
            {
                if ((isAdminModule | (IsAdminControl() & (ctlString == "Module"))) | (IsAdminControl() & (ctlString == "Tab")))
                {
                    HelpUrl = Conversions.ToString(HostSettings["HelpURL"]);
                }
                return HelpUrl;
            }
            HelpUrl = "";
            return HelpUrl;
        }

        public static string GetPortalDomainName(string strPortalAlias, [Optional, DefaultParameterValue(null)] HttpRequest Request, [Optional, DefaultParameterValue(true)] bool blnAddHTTP)
        {
            string strDomainName = "";
            string strURL = "";
            if (Request != null)
            {
                strURL = GetDomainName(Request);
            }
            string[] arrPortalAlias = Strings.Split(strPortalAlias, ",", -1, CompareMethod.Binary);
            int refIntHelperL0 = arrPortalAlias.Length - 1;
            for (int intAlias = 0; intAlias <= refIntHelperL0; intAlias++)
            {
                if (arrPortalAlias[intAlias] == strURL)
                {
                    strDomainName = arrPortalAlias[intAlias];
                }
            }
            if (strDomainName == "")
            {
                strDomainName = arrPortalAlias[0];
            }
            if (blnAddHTTP)
            {
                strDomainName = AddHTTP(strDomainName);
            }
            return strDomainName;
        }

        public static PortalSettings GetPortalSettings()
        {
            PortalSettings portalSettings = null;
            if (HttpContext.Current != null)
            {
                portalSettings = (PortalSettings) HttpContext.Current.Items["PortalSettings"];
            }
            if (portalSettings == null)
            {
                portalSettings = GetHostPortalSettings();
            }
            return portalSettings;
        }

        public static ArrayList GetPortalTabs(ArrayList objDesktopTabs, bool blnNoneSpecified, bool blnHidden)
        {
            return GetPortalTabs(objDesktopTabs, -1, blnNoneSpecified, blnHidden, false, false, false);
        }

        public static ArrayList GetPortalTabs(ArrayList objDesktopTabs, bool blnNoneSpecified, bool blnHidden, bool blnDeleted, bool blnURL)
        {
            return GetPortalTabs(objDesktopTabs, -1, blnNoneSpecified, blnHidden, blnDeleted, blnURL, false);
        }

        public static ArrayList GetPortalTabs(int intPortalId, bool blnNoneSpecified, bool blnHidden, bool blnDeleted, bool blnURL, bool bCheckAuthorised)
        {
            TabController objTabs = new TabController();
            PortalSettings _portalSettings = PortalController.GetCurrentPortalSettings();
            if (intPortalId == _portalSettings.PortalId)
            {
                return GetPortalTabs(_portalSettings.DesktopTabs, -1, blnNoneSpecified, blnHidden, blnDeleted, blnURL, bCheckAuthorised);
            }
            ArrayList arrTabs = (ArrayList) DotNetNuke.UI.Utilities.DataCache.GetCache("GetTabs" + intPortalId.ToString());
            if (arrTabs == null)
            {
                arrTabs = objTabs.GetTabs(intPortalId);
            }
            return GetPortalTabs(arrTabs, -1, blnNoneSpecified, blnHidden, blnDeleted, blnURL, bCheckAuthorised);
        }

        public static ArrayList GetPortalTabs(ArrayList objDesktopTabs, int currentTab, bool blnNoneSpecified, bool blnHidden, bool blnDeleted, bool blnURL, bool bCheckAuthorised)
        {
            DotNetNuke.Entities.Tabs.TabInfo objTab;
            IEnumerator refObjectHelperL0=null;
            ArrayList arrPortalTabs = new ArrayList();
            if (blnNoneSpecified)
            {
                objTab = new DotNetNuke.Entities.Tabs.TabInfo();
                objTab.TabID = -1;
                objTab.TabName = "<" + DotNetNuke.Services.Localization.Localization.GetString("None_Specified") + ">";
                objTab.TabOrder = 0;
                objTab.ParentId = -2;
                arrPortalTabs.Add(objTab);
            }
            try
            {
                refObjectHelperL0 = objDesktopTabs.GetEnumerator();
                while (refObjectHelperL0.MoveNext())
                {
                    objTab = (DotNetNuke.Entities.Tabs.TabInfo) refObjectHelperL0.Current;
                    if (((currentTab < 0) | (objTab.TabID != currentTab)) && (((!objTab.IsAdminTab & (objTab.IsVisible | blnHidden)) & (!objTab.IsDeleted | blnDeleted)) & ((objTab.TabType == TabType.Normal) | blnURL)))
                    {
                        DotNetNuke.Entities.Tabs.TabInfo tabTemp = objTab.Clone();
                        string strIndent = "";
                        int refIntHelperL0 = tabTemp.Level;
                        for (int intCounter = 1; intCounter <= refIntHelperL0; intCounter++)
                        {
                            strIndent = strIndent + "...";
                        }
                        tabTemp.TabName = strIndent + tabTemp.TabName;
                        if (bCheckAuthorised)
                        {
                            if (PortalSecurity.IsInRoles(tabTemp.AdministratorRoles))
                            {
                                arrPortalTabs.Add(tabTemp);
                            }
                        }
                        else
                        {
                            arrPortalTabs.Add(tabTemp);
                        }
                    }
                }
            }
            finally
            {
                if (refObjectHelperL0 is IDisposable)
                {
                    (refObjectHelperL0 as IDisposable).Dispose();
                }
            }
            return arrPortalTabs;
        }

        public static string GetRoleName(int RoleID)
        {
            if (Convert.ToString(RoleID) == "-1")
            {
                return "All Users";
            }
            if (Convert.ToString(RoleID) == "-3")
            {
                return "Unauthenticated Users";
            }
            Hashtable htRoles = null;
            if (PerformanceSetting != PerformanceSettings.NoCaching)
            {
                htRoles = (Hashtable) DotNetNuke.UI.Utilities.DataCache.GetCache("GetRoles");
            }
            if (htRoles == null)
            {
                ArrayList arrRoles = new RoleController().GetRoles();
                htRoles = new Hashtable();
                int refIntHelperL0 = arrRoles.Count - 1;
                for (int i = 0; i <= refIntHelperL0; i++)
                {
                    RoleInfo objRole = (RoleInfo) arrRoles[i];
                    htRoles.Add(objRole.RoleID, objRole.RoleName);
                }
                if (PerformanceSetting != PerformanceSettings.NoCaching)
                {
                    DotNetNuke.UI.Utilities.DataCache.SetCache("GetRoles", htRoles);
                }
            }
            return Conversions.ToString(htRoles[RoleID]);
        }

        public static string GetShortDate(string strDate)
        {
            if (strDate != "")
            {
                DateTime datDate = Convert.ToDateTime(strDate);
                string strYear = DateAndTime.Year(datDate).ToString();
                string strMonth = DateAndTime.Month(datDate).ToString();
                string strDay = DateAndTime.Day(datDate).ToString();
                strDate = strMonth + "/" + strDay + "/" + strYear;
            }
            return strDate;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Returns the folder path under the root for the portal 
        /// </summary>
        /// <param name="strFileNamePath">The folder the absolute path</param>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [cnurse] 16/9/2004  Updated for localization, Help and 508
        /// [Philip Beadle] 6 October 2004 Moved to Globals from WebUpload.ascx.vb so can be accessed by URLControl.ascx
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string GetSubFolderPath(string strFileNamePath)
        {
            string ParentFolderName;
            PortalSettings _portalSettings = PortalController.GetCurrentPortalSettings();
            if (_portalSettings.ActiveTab.ParentId == _portalSettings.SuperTabId)
            {
                ParentFolderName = HostMapPath.Replace("/", @"\");
            }
            else
            {
                ParentFolderName = _portalSettings.HomeDirectoryMapPath.Replace("/", @"\");
            }
            return strFileNamePath.Substring(0, strFileNamePath.LastIndexOf(@"\") + 1).Substring(ParentFolderName.Length).Replace(@"\", "/");
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// GetUpgradeStatus - determines whether an upgrade/install is required
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <returns>An UpgradeStatus enum Upgrade/Install/None</returns>
        /// <history>
        /// [cnurse]	02/02/2004	created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static UpgradeStatus GetUpgradeStatus()
        {
            bool useConfig;
            string strAssemblyVersion = "04.00.00".Replace(".", "");
            string strDatabaseVersion = "";
            string strConfirmVersion = "";
            XmlDocument xmlConfig = new XmlDocument();
            UpgradeStatus status = UpgradeStatus.None;
            if (Config.GetSection("dotnetnuke/data") == null)
            {
                return UpgradeStatus.Install;
            }
            if (Config.GetSetting("UseDnnConfig") == null)
            {
                useConfig = false;
            }
            else
            {
                useConfig = bool.Parse(Config.GetSetting("UseDnnConfig"));
            }
            if (useConfig && System.IO.File.Exists(ApplicationMapPath + @"\Install\dnn.config"))
            {
                try
                {
                    xmlConfig.Load(ApplicationMapPath + @"\Install\dnn.config");
                    XmlNode node = xmlConfig.SelectSingleNode("dotnetnuke");
                    if (node != null)
                    {
                        strDatabaseVersion = XmlUtils.GetNodeValue(node, "version", "");
                    }
                }
                catch (Exception exception1)
                {
                    
                    Exception exc = exception1;
                    strDatabaseVersion = "";
                    
                }
            }
            if (strDatabaseVersion == "")
            {
                string strProviderPath = PortalSettings.GetProviderPath();
                if (!strProviderPath.StartsWith("ERROR:"))
                {
                    strDatabaseVersion = GetDatabaseVersion();
                }
                else
                {
                    strDatabaseVersion = strProviderPath;
                }
            }
            else if (strDatabaseVersion != strAssemblyVersion)
            {
                strConfirmVersion = GetDatabaseVersion();
                if (strConfirmVersion != strDatabaseVersion)
                {
                    strDatabaseVersion = strConfirmVersion;
                    if (useConfig)
                    {
                        SaveDatabaseVersion(strDatabaseVersion);
                    }
                }
            }
            if (strDatabaseVersion.StartsWith("ERROR"))
            {
                return UpgradeStatus.Error;
            }
            if (strDatabaseVersion == "")
            {
                return UpgradeStatus.Install;
            }
            if (strDatabaseVersion != strAssemblyVersion)
            {
                status = UpgradeStatus.Upgrade;
            }
            return status;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Returns the type of URl (T=other tab, F=file, U=URL, N=normal)
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="URL">The url</param>
        /// <returns>The url type</returns>
        /// <history>
        /// [cnurse]	12/16/2004	documented
        /// </history>
        /// -----------------------------------------------------------------------------
        public static TabType GetURLType(string URL)
        {
            if (URL == "")
            {
                return TabType.Normal;
            }
            if ((((!URL.ToLower().StartsWith("mailto:") & (URL.IndexOf("://") == -1)) & !URL.StartsWith("~")) & !URL.StartsWith(@"\\")) & !URL.StartsWith("/"))
            {
                if (Versioned.IsNumeric(URL))
                {
                    return TabType.Tab;
                }
                return TabType.File;
            }
            return TabType.Url;
        }

        public static string HTTPPOSTEncode(string strPost)
        {
            strPost = Strings.Replace(strPost, @"\", "", 1, -1, CompareMethod.Binary);
            strPost = HttpUtility.UrlEncode(strPost);
            strPost = Strings.Replace(strPost, "%2f", "/", 1, -1, CompareMethod.Binary);
            return strPost;
        }

        public static string ImportUrl(int ModuleId, string url)
        {
            string strUrl = url;
            if (GetURLType(url) == TabType.File)
            {
                ModuleController objModuleController = new ModuleController();
                FileController objFileController = new FileController();
                ModuleInfo objModule = objModuleController.GetModule(ModuleId, Null.NullInteger);
                strUrl = "FileID=" + objFileController.ConvertFilePathToFileId(url, objModule.PortalID).ToString();
            }
            return strUrl;
        }

        public static bool IsAdminControl()
        {
            if (HttpContext.Current == null)
            {
                return false;
            }
            return (!Information.IsNothing(HttpContext.Current.Request.QueryString["mid"]) | !Information.IsNothing(HttpContext.Current.Request.QueryString["ctl"]));
        }

        public static bool IsAdminSkin(bool IsAdminTab)
        {
            string AdminKeys = "tab,module,importmodule,exportmodule,help";
            string ControlKey = "";
            if (HttpContext.Current.Request.QueryString["ctl"] != null)
            {
                ControlKey = HttpContext.Current.Request.QueryString["ctl"].ToLower();
            }
            int ModuleID = -1;
            if (HttpContext.Current.Request.QueryString["mid"] != null)
            {
                ModuleID = int.Parse(HttpContext.Current.Request.QueryString["mid"]);
            }
            if (!IsAdminTab && !(((ControlKey != "") & (ControlKey != "view")) & (ModuleID != -1)))
            {
            }
            return (((ControlKey != "") & (AdminKeys.IndexOf(ControlKey) != -1)) & (ModuleID == -1));
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Returns whether the currnet tab is in LayoutMode
        /// </summary>
        /// <returns></returns>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [Jon Henning]	9/16/2004	Created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static bool IsLayoutMode()
        {
            bool blnReturn = false;
            PortalSettings _portalSettings = PortalController.GetCurrentPortalSettings();
            if (((((PortalSecurity.IsInRole(_portalSettings.AdministratorRoleName.ToString()) || PortalSecurity.IsInRoles(_portalSettings.ActiveTab.AdministratorRoles.ToString())) && !IsTabPreview()) ? 1 : 0) != 0) && !_portalSettings.ActiveTab.IsAdminTab)
            {
                blnReturn = true;
            }
            return blnReturn;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Returns whether the tab being displayed is in preview mode
        /// </summary>
        /// <returns></returns>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [Jon Henning]	9/16/2004	Created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static bool IsTabPreview()
        {
            bool blnReturn = false;
            PortalSettings _portalSettings = PortalController.GetCurrentPortalSettings();
            if ((((HttpContext.Current.Request != null) && (HttpContext.Current.Request.Cookies["_Tab_Admin_Preview" + _portalSettings.PortalId.ToString()] != null)) ? 1 : 0) != 0)
            {
                blnReturn = bool.Parse(HttpContext.Current.Request.Cookies["_Tab_Admin_Preview" + _portalSettings.PortalId.ToString()].Value);
            }
            return blnReturn;
        }

        public static string LinkClick(string Link, int TabID, int ModuleID)
        {
            return LinkClick(Link, TabID, ModuleID, true, "");
        }

        public static string LinkClick(string Link, int TabID, int ModuleID, bool TrackClicks)
        {
            return LinkClick(Link, TabID, ModuleID, TrackClicks, "");
        }

        public static string LinkClick(string Link, int TabID, int ModuleID, bool TrackClicks, string ContentType)
        {
            string strLink = Link;
            if (TrackClicks | (ContentType != ""))
            {
                strLink = (ApplicationPath + "/LinkClick.aspx?link=" + HttpUtility.UrlEncode(strLink)) + "&tabid=" + TabID.ToString();
                if (ModuleID != -1)
                {
                    strLink = strLink + "&mid=" + ModuleID.ToString();
                }
                if (ContentType != "")
                {
                    strLink = strLink + "&contenttype=" + ContentType;
                }
                return strLink;
            }
            return LinkClickURL(strLink);
        }

        public static string LinkClickURL(string Link)
        {
            string strLink = Link;
            switch (GetURLType(strLink))
            {
                case TabType.File:
                    return (PortalController.GetCurrentPortalSettings().HomeDirectory + Link);

                case TabType.Normal:
                    return strLink;

                case TabType.Tab:
                    return (ApplicationPath + "/Default.aspx?tabid=" + Link);
            }
            return strLink;
        }

        public static string ManageUploadDirectory(string strHTML, string strUploadDirectory)
        {
            string ManageUploadDirectory = "";
            if (strHTML != "")
            {
                int P;
                for (P = Strings.InStr(1, strHTML.ToLower(), "src=\"", CompareMethod.Binary); P != 0; P = Strings.InStr(1, strHTML.ToLower(), "src=\"", CompareMethod.Binary))
                {
                    ManageUploadDirectory = ManageUploadDirectory + Strings.Left(strHTML, P + 4);
                    strHTML = Strings.Mid(strHTML, P + 5);
                    if (Strings.InStr(1, strHTML, "://", CompareMethod.Binary) == 0)
                    {
                        strHTML = strUploadDirectory + strHTML;
                    }
                }
                strHTML = ManageUploadDirectory + strHTML;
                ManageUploadDirectory = "";
                for (P = Strings.InStr(1, strHTML.ToLower(), "background=\"", CompareMethod.Binary); P != 0; P = Strings.InStr(1, strHTML.ToLower(), "background=\"", CompareMethod.Binary))
                {
                    ManageUploadDirectory = ManageUploadDirectory + Strings.Left(strHTML, P + 11);
                    strHTML = Strings.Mid(strHTML, P + 12);
                    if (Strings.InStr(1, strHTML, "://", CompareMethod.Binary) == 0)
                    {
                        strHTML = strUploadDirectory + strHTML;
                    }
                }
            }
            return (ManageUploadDirectory + strHTML);
        }

        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public static string NavigateURL()
        {
            return NavigateURL(PortalController.GetCurrentPortalSettings().ActiveTab.TabID, Null.NullString);
        }

        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public static string NavigateURL(int TabID)
        {
            return NavigateURL(TabID, Null.NullString);
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
        public static string NavigateURL(string ControlKey)
        {
            return NavigateURL(PortalController.GetCurrentPortalSettings().ActiveTab.TabID, ControlKey);
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
        public static string NavigateURL(int TabID, bool IsSuperTab)
        {
            PortalSettings _portalSettings = PortalController.GetCurrentPortalSettings();
            return NavigateURL(TabID, IsSuperTab, _portalSettings, Null.NullString, null);
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
        public static string NavigateURL(int TabID, string ControlKey)
        {
            return NavigateURL(TabID, ControlKey, null);
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
        public static string NavigateURL(int TabID, string ControlKey, params string[] AdditionalParameters)
        {
            PortalSettings _portalSettings = PortalController.GetCurrentPortalSettings();
            return NavigateURL(TabID, _portalSettings, ControlKey, AdditionalParameters);
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
        public static string NavigateURL(int TabID, PortalSettings settings, string ControlKey, params string[] AdditionalParameters)
        {
            bool isSuperTab = false;
            if ((settings != null) && settings.ActiveTab.IsSuperTab)
            {
                isSuperTab = true;
            }
            return NavigateURL(TabID, isSuperTab, settings, ControlKey, AdditionalParameters);
        }

        public static string NavigateURL(int TabID, bool IsSuperTab, PortalSettings settings, string ControlKey, params string[] AdditionalParameters)
        {
            string strURL;
            if (TabID == Null.NullInteger)
            {
                strURL = ApplicationURL();
            }
            else
            {
                strURL = ApplicationURL(TabID);
            }
            if (ControlKey != "")
            {
                strURL = strURL + "&ctl=" + ControlKey;
            }
            if (AdditionalParameters != null)
            {
                foreach (string parameter in AdditionalParameters)
                {
                    strURL = strURL + "&" + parameter;
                }
            }
            if (IsSuperTab)
            {
                strURL = strURL + "&portalid=" + settings.PortalId.ToString();
            }
            if (DotNetNuke.Entities.Host.HostSettings.GetHostSetting("UseFriendlyUrls") == "Y")
            {
                IEnumerator refObjectHelperL0=null;
                try
                {
                    refObjectHelperL0 = settings.DesktopTabs.GetEnumerator();
                    while (refObjectHelperL0.MoveNext())
                    {
                        DotNetNuke.Entities.Tabs.TabInfo objTab = (DotNetNuke.Entities.Tabs.TabInfo) refObjectHelperL0.Current;
                        if (objTab.TabID == TabID)
                        {
                            return FriendlyUrl(objTab, strURL, settings);
                        }
                    }
                }
                finally
                {
                    if (refObjectHelperL0 is IDisposable)
                    {
                        (refObjectHelperL0 as IDisposable).Dispose();
                    }
                }
                return FriendlyUrl(null, strURL, settings);
            }
            return ResolveUrl(strURL);
        }

        public static string PreventSQLInjection(string strSQL)
        {
            return new PortalSecurity().InputFilter(strSQL, PortalSecurity.FilterFlag.NoSQL);
        }

        public static string QueryStringDecode(string QueryString)
        {
            QueryString = HttpUtility.UrlDecode(QueryString);
            try
            {
                string fullPath = HttpContext.Current.Request.MapPath(QueryString, HttpContext.Current.Request.ApplicationPath, false);
            }
            catch (HttpException exception1)
            {
                
                HttpException ex = exception1;
                throw new HttpException(0x194, "Not Found");
                
            }
            string strDoubleDecodeURL = HttpContext.Current.Server.UrlDecode(HttpContext.Current.Server.UrlDecode(QueryString));
            if ((QueryString.IndexOf("..") != -1) | (strDoubleDecodeURL.IndexOf("..") != -1))
            {
                throw new HttpException(0x194, "Not Found");
            }
            return QueryString;
        }

        public static string QueryStringEncode(string QueryString)
        {
            QueryString = HttpUtility.UrlEncode(QueryString);
            return QueryString;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Generates the correctly formatted url
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="url">The url to format.</param>
        /// <returns>The formatted (resolved) url</returns>
        /// <history>
        /// [cnurse]	12/16/2004	documented
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string ResolveUrl(string url)
        {
            if (url.Length == 0)
            {
                return url;
            }
            if (!url.StartsWith("~"))
            {
                return url;
            }
            if (url.Length == 1)
            {
                return ApplicationPath;
            }
            if ((Conversions.ToString(url.ToCharArray()[1]) == "/") | (Conversions.ToString(url.ToCharArray()[1]) == @"\"))
            {
                if (ApplicationPath.Length > 1)
                {
                    return (ApplicationPath + "/" + url.Substring(2));
                }
                return ("/" + url.Substring(2));
            }
            if (ApplicationPath.Length > 1)
            {
                return (ApplicationPath + "/" + url.Substring(1));
            }
            return (ApplicationPath + url.Substring(1));
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// SaveDatabaseVersion - saves the current version to the config file
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [cnurse]	02/02/2004	created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static void SaveDatabaseVersion(string strVersion)
        {
            XmlDocument xmlConfig = new XmlDocument();
            XmlNode nodeConfig = xmlConfig.AppendChild(xmlConfig.CreateElement("dotnetnuke"));
            XmlElement node = xmlConfig.CreateElement("version");
            node.InnerXml = strVersion;
            nodeConfig.AppendChild(node);
            xmlConfig.Save(ApplicationMapPath + @"\Install\dnn.config");
        }

        [Obsolete("This function has been replaced by DotNetNuke.Services.Mail.Mail.SendMail")]
        public static string SendMail(string MailFrom, string MailTo, string Cc, string Bcc, MailPriority Priority, string Subject, MailFormat BodyFormat, Encoding BodyEncoding, string Body, string Attachment, string SMTPServer, string SMTPAuthentication, string SMTPUsername, string SMTPPassword)
        {
            return DotNetNuke.Services.Mail.Mail.SendMail(MailFrom, MailTo, Cc, Bcc, Priority, Subject, BodyFormat, BodyEncoding, Body, Attachment, SMTPServer, SMTPAuthentication, SMTPUsername, SMTPPassword);
        }

        [Obsolete("This function has been replaced by DotNetNuke.Services.Mail.Mail.SendMail")]
        public static string SendNotification(string MailFrom, string MailTo, string Bcc, string Subject, string Body)
        {
            return DotNetNuke.Services.Mail.Mail.SendMail(MailFrom, MailTo, Bcc, Subject, Body, "", "", "", "", "", "");
        }

        [Obsolete("This function has been replaced by DotNetNuke.Services.Mail.Mail.SendMail")]
        public static string SendNotification(string MailFrom, string MailTo, string Bcc, string Subject, string Body, string Attachment)
        {
            return DotNetNuke.Services.Mail.Mail.SendMail(MailFrom, MailTo, Bcc, Subject, Body, Attachment, "", "", "", "", "");
        }

        [Obsolete("This function has been replaced by DotNetNuke.Services.Mail.Mail.SendMail")]
        public static string SendNotification(string MailFrom, string MailTo, string Bcc, string Subject, string Body, string Attachment, string BodyType)
        {
            return DotNetNuke.Services.Mail.Mail.SendMail(MailFrom, MailTo, Bcc, Subject, Body, Attachment, BodyType, "", "", "", "");
        }

        [Obsolete("This function has been replaced by DotNetNuke.Services.Mail.Mail.SendMail")]
        public static string SendNotification(string MailFrom, string MailTo, string Bcc, string Subject, string Body, string Attachment, string BodyType, string SMTPServer, string SMTPAuthentication, string SMTPUsername, string SMTPPassword)
        {
            return DotNetNuke.Services.Mail.Mail.SendMail(MailFrom, MailTo, Bcc, Subject, Body, Attachment, BodyType, SMTPServer, SMTPAuthentication, SMTPUsername, SMTPPassword);
        }

        [Obsolete("This function has been replaced by DotNetNuke.Services.Mail.Mail.SendMail")]
        public static string SendNotification(string MailFrom, string MailTo, string Cc, string Bcc, MailPriority Priority, string Subject, MailFormat BodyFormat, Encoding BodyEncoding, string Body, string Attachment, string SMTPServer, string SMTPAuthentication, string SMTPUsername, string SMTPPassword)
        {
            return DotNetNuke.Services.Mail.Mail.SendMail(MailFrom, MailTo, Cc, Bcc, Priority, Subject, BodyFormat, BodyEncoding, Body, Attachment, SMTPServer, SMTPAuthentication, SMTPUsername, SMTPPassword);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// SerializeHashTableBase64 serializes a Hashtable using Binary Formatting
        /// </summary>
        /// <remarks>
        /// While this method of serializing is no longer supported (due to Medium Trust
        /// issue, it is still required for upgrade purposes.
        /// </remarks>
        /// <param name="Source">The Hashtable to serialize</param>
        /// <returns>The serialized String</returns>
        /// <history>
        /// [cnurse]	2/16/2005	moved to Globals
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string SerializeHashTableBase64(Hashtable Source)
        {
            if (Source.Count != 0)
            {
                string strString;
                BinaryFormatter bin = new BinaryFormatter();
                MemoryStream mem = new MemoryStream();
                try
                {
                    bin.Serialize(mem, Source);
                    strString = Convert.ToBase64String(mem.GetBuffer(), 0, Convert.ToInt32(mem.Length));
                }
                catch (Exception exception1)
                {
                    
                    Exception ex = exception1;
                    strString = "";
                    
                }
                finally
                {
                    mem.Close();
                }
                return strString;
            }
            return "";
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// SerializeHashTableXml serializes a Hashtable using Xml Serialization
        /// </summary>
        /// <remarks>
        /// This is the preferred method of serialization under Medium Trust
        /// </remarks>
        /// <param name="Source">The Hashtable to serialize</param>
        /// <returns>The serialized String</returns>
        /// <history>
        /// [cnurse]	2/16/2005	moved to Globals
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string SerializeHashTableXml(Hashtable Source)
        {
            if (Source.Count != 0)
            {
                IEnumerator refObjectHelperL0=null;
                XmlDocument xmlProfile = new XmlDocument();
                XmlElement xmlRoot = xmlProfile.CreateElement("profile");
                xmlProfile.AppendChild(xmlRoot);
                try
                {
                    refObjectHelperL0 = Source.Keys.GetEnumerator();
                    while (refObjectHelperL0.MoveNext())
                    {
                        string key = Conversions.ToString(refObjectHelperL0.Current);
                        XmlElement xmlItem = xmlProfile.CreateElement("item");
                        xmlItem.SetAttribute("key", key);
                        xmlItem.SetAttribute("type", Source[key].GetType().AssemblyQualifiedName.ToString());
                        XmlDocument xmlObject = new XmlDocument();
                        XmlSerializer xser = new XmlSerializer(Source[key].GetType());
                        StringWriter sw = new StringWriter();
                        xser.Serialize((TextWriter) sw, RuntimeHelpers.GetObjectValue(Source[key]));
                        xmlObject.LoadXml(sw.ToString());
                        xmlItem.AppendChild(xmlProfile.ImportNode(xmlObject.DocumentElement, true));
                        xmlRoot.AppendChild(xmlItem);
                    }
                }
                finally
                {
                    if (refObjectHelperL0 is IDisposable)
                    {
                        (refObjectHelperL0 as IDisposable).Dispose();
                    }
                }
                return xmlProfile.OuterXml;
            }
            return "";
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Sets the ApplicationName for the MemberRole API
        /// </summary>
        /// <remarks>
        /// This overload takes a the PortalId
        /// </remarks>
        /// <param name="PortalID">The Portal Id</param>
        /// <history>
        /// [cnurse]	01/18/2005	documented
        /// </history>
        /// -----------------------------------------------------------------------------
        public static void SetApplicationName(int PortalID)
        {
            HttpContext.Current.Items["ApplicationName"] = GetApplicationName(PortalID);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Sets the ApplicationName for the MemberRole API
        /// </summary>
        /// <remarks>
        /// This overload takes a the PortalId
        /// </remarks>
        /// <param name="ApplicationName">The Application Name to set</param>
        /// <history>
        /// [cnurse]	01/18/2005	documented
        /// </history>
        /// -----------------------------------------------------------------------------
        public static void SetApplicationName(string ApplicationName)
        {
            HttpContext.Current.Items["ApplicationName"] = ApplicationName;
        }

        public static void SetFormFocus(Control control)
        {
            if (((control.Page != null) & control.Visible) && (control.Page.Request.Browser.EcmaScriptVersion.Major >= 1))
            {
                if (!ClientAPI.ClientAPIDisabled())
                {
                    ClientAPI.RegisterClientReference(control.Page, ClientAPI.ClientNamespaceReferences.dnn);
                    DNNClientAPI.AddBodyOnloadEventHandler(control.Page, "__dnn_SetInitialFocus('" + control.ClientID + "');");
                }
                else
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("<SCRIPT LANGUAGE='JavaScript'>");
                    sb.Append("<!--");
                    sb.Append('\n');
                    sb.Append("function SetInitialFocus() {");
                    sb.Append('\n');
                    sb.Append(" document.");
                    Control objParent = control.Parent;
                    while (!(objParent is HtmlForm))
                    {
                        objParent = objParent.Parent;
                    }
                    sb.Append(objParent.ClientID);
                    sb.Append("['");
                    sb.Append(control.UniqueID);
                    sb.Append("'].focus(); }");
                    sb.Append("window.onload = SetInitialFocus;");
                    sb.Append('\n');
                    sb.Append("// -->");
                    sb.Append('\n');
                    sb.Append("</SCRIPT>");
                    ClientAPI.RegisterClientScriptBlock(control.Page, "InitialFocus", sb.ToString());
                }
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// UploadFile pocesses a single file 
        /// </summary>
        /// <param name="RootPath">The folder wherr the file will be put</param>
        /// <param name="objHtmlInputFile">The file to upload</param>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [cnurse] 16/9/2004  Updated for localization, Help and 508
        /// [Philip Beadle] 6 October 2004 Moved to Globals from WebUpload.ascx.vb so can be accessed by URLControl.ascx
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string UploadFile(string RootPath, HttpPostedFile objHtmlInputFile, [Optional, DefaultParameterValue(false)] bool Unzip)
        {
            PortalSettings _portalSettings = PortalController.GetCurrentPortalSettings();
            PortalController objPortalController = new PortalController();
            string strMessage = "";
            string strFileName = RootPath + Path.GetFileName(objHtmlInputFile.FileName);
            string strExtension = Strings.Replace(Path.GetExtension(strFileName), ".", "", 1, -1, CompareMethod.Binary);
            if ((((((double) (objPortalController.GetPortalSpaceUsed(_portalSettings.PortalId) + objHtmlInputFile.ContentLength)) / 1000000.0) <= _portalSettings.HostSpace) | (_portalSettings.HostSpace == 0)) | (_portalSettings.ActiveTab.ParentId == _portalSettings.SuperTabId))
            {
                if ((Strings.InStr(1, "," + _portalSettings.HostSettings["FileExtensions"].ToString().ToUpper(), "," + strExtension.ToUpper(), CompareMethod.Binary) != 0) | (_portalSettings.ActiveTab.ParentId == _portalSettings.SuperTabId))
                {
                    try
                    {
                        if (System.IO.File.Exists(strFileName))
                        {
                            System.IO.File.SetAttributes(strFileName, FileAttributes.Normal);
                            System.IO.File.Delete(strFileName);
                        }
                        objHtmlInputFile.SaveAs(strFileName);
                        if ((Path.GetExtension(strFileName).ToLower() == ".zip") & Unzip)
                        {
                            return (strMessage + FileSystemUtils.UnzipFile(strFileName, RootPath, _portalSettings));
                        }
                        AddFile(strFileName, strExtension, objHtmlInputFile.ContentType);
                        return strMessage;
                    }
                    catch (Exception exception1)
                    {
                        
                        Exception Exc = exception1;
                        strMessage = strMessage + "<br>" + string.Format(DotNetNuke.Services.Localization.Localization.GetString("SaveFileError"), strFileName);
                        
                    }
                    return strMessage;
                }
                return (strMessage + "<br>" + string.Format(DotNetNuke.Services.Localization.Localization.GetString("RestrictedFileType"), strFileName, Strings.Replace(_portalSettings.HostSettings["FileExtensions"].ToString(), ",", ", *.", 1, -1, CompareMethod.Binary)));
            }
            return (strMessage + "<br>" + string.Format(DotNetNuke.Services.Localization.Localization.GetString("DiskSpaceExceeded"), strFileName));
        }

        [Obsolete("This function has been replaced by DotNetNuke.Common.Utilities.XmlUtils.XMLEncode")]
        public static string XMLEncode(string HTML)
        {
            return XmlUtils.XMLEncode(HTML);
        }

        public static string ApplicationMapPath
        {
            get
            {
                return _ApplicationMapPath;
            }
            set
            {
                _ApplicationMapPath = value;
            }
        }

        public static string ApplicationPath
        {
            get
            {
                return _ApplicationPath;
            }
            set
            {
                _ApplicationPath = value;
            }
        }

        public static string AssemblyPath
        {
            get
            {
                return _AssemblyPath;
            }
            set
            {
                _AssemblyPath = value;
            }
        }

        public static string HostMapPath
        {
            get
            {
                return _HostMapPath;
            }
            set
            {
                _HostMapPath = value;
            }
        }

        public static string HostPath
        {
            get
            {
                return _HostPath;
            }
            set
            {
                _HostPath = value;
            }
        }

        public static Hashtable HostSettings
        {
            get
            {
                return DotNetNuke.Entities.Host.HostSettings.GetHostSettings();
            }
        }

        public static PerformanceSettings PerformanceSetting
        {
            get
            {
                return (PerformanceSettings) Convert.ToInt32(RuntimeHelpers.GetObjectValue(Interaction.IIf(HostSettings["PerformanceSetting"] == null, 3, RuntimeHelpers.GetObjectValue(HostSettings["PerformanceSetting"]))));
            }
        }

        public static string ServerName
        {
            get
            {
                return _ServerName;
            }
            set
            {
                _ServerName = value;
            }
        }

        public static bool WebFarmEnabled
        {
            get
            {
                return ((Config.GetSetting("EnableWebFarmSupport") != null) && (Config.GetSetting("EnableWebFarmSupport").ToLower() == "true"));
            }
        }

        public enum PerformanceSettings
        {
            HeavyCaching = 6,
            LightCaching = 1,
            ModerateCaching = 3,
            NoCaching = 0
        }

        public enum PortalRegistrationType
        {
            NoRegistration,
            PrivateRegistration,
            PublicRegistration,
            VerifiedRegistration
        }

        public enum UpgradeStatus
        {
            Upgrade,
            Install,
            None,
            Error
        }
    }
}

